package com.hurl.waguji.biz.download;

import java.util.List;

import org.testng.log4testng.Logger;

import com.hurl.library.http.HttpException;
import com.hurl.library.http.HttpRequest;
import com.hurl.library.spider.UrlPattern;
import com.hurl.library.util.StringUtils;
import com.hurl.waguji.base.Formatter;
import com.hurl.waguji.base.dataprocess.ProcessParams;
import com.hurl.waguji.persistence.DmGpBO;
import com.hurl.waguji.persistence.JcsjGpHyBO;
import com.hurl.waguji.persistence.JcsjHytjThsBO;

class HytjThsProcessor extends BaseDownloadForUpdateProcessor {
	public HytjThsProcessor(ProcessParams params, DownloadIdentifier identifier) {
		super(params, identifier);
	}
	private HttpRequest request = new HttpRequest();
	private static final Logger log = Logger.getLogger(HytjThsProcessor.class);
	private UniqueChecker checker = UniqueChecker.getInstance();


	@Override
	public void convertHTML2BO(String url, String html, BOSaver collector) {

		if(StringUtils.isBlank(html)){
			return ;
		}
		String hydm = StringUtils.substringBetween(html, "<li>","行业分析");
		hydm = StringUtils.substringBetween(hydm, "<a href=\"../trade/",".html");
		if(StringUtils.isBlank(hydm)){
			return ;
		}

		url = "http://basic.10jqka.com.cn/trade/"+hydm+".html";
		try {
			html = request.request(url);
		} catch (HttpException e) {
			log.error(e);
		}
		if(StringUtils.isBlank(html)){
			return ;
		}
		String hymc = StringUtils.substringBetween(html, "所属行业: <span>", "</span>");
		
		JcsjGpHyBO bo = new JcsjGpHyBO();
		bo.setGpdm(context.getEnvAsString("gpdm"));
		bo.setHydm(hydm);
		bo.setHymc(hymc);
		collector.addBO(bo);

		if(!checker.isUnique(hydm)){
			log.error("重复的行业代码："+hydm);
			return;
		}
		
		url = "http://basic.10jqka.com.cn/trade/xml/"+hydm+".xml";
		try {
			html = request.request(url);
		} catch (HttpException e) {
			log.error(e);
		}
		
		if(StringUtils.isBlank(html)){
			return ;
		}
		
		hydm = Formatter.toString(hydm);
		JcsjHytjThsBO hy = null;
		hy = context.getDao().get(JcsjHytjThsBO.class,hydm);
		if(hy==null){
			hy = new JcsjHytjThsBO();
		}
		hy.setHydm(hydm);
		hy.setHymc(hymc);
		List<String> itemlist = StringUtils.substringsBetween(html, "<item value='","'>");
		hy.setYl(Formatter.toInteger(itemlist.get(0)));
		hy.setKs(Formatter.toInteger(itemlist.get(1)));
		hy.setCp(Formatter.toInteger(itemlist.get(2)));
		hy.setLastupdate(currentTime);
		collector.addBO(hy);
	}

	@Override
	public UrlPattern getUrlPattern() {
		return new StockIteratorUrlPattern(context) {
			@Override
			public String bo2url(DmGpBO bo) {
				return "http://basic.10jqka.com.cn/"+bo.getGpDmJ()+"/head.html";
			}
		};
	}


}
